package com.wl156.services;

import java.io.IOException;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.activities.InternalMessage;
import com.wl156.activities.MessageCenter;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;
import com.wl156.model.Wl156DB;
import com.wl156.utils.Utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class MyService extends Service {

	private static final String TAG = null;
	private static final int HELLO_ID = 1;

	private Looper mServiceLooper;
	private ServiceHandler mServcieHandler;

	private WebServiceClient mWebServiceClient;
	// private Certificate mCertificate;

	NotificationManager mNotificationManager;

	LocationManager locationManager;

	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.d(TAG, "msg: " + msg);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		mWebServiceClient = new WebServiceClient(this);
		// mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		HandlerThread thread = new HandlerThread("CheckInternalMessageThread",
				HandlerThread.MIN_PRIORITY);
		thread.start();

		mServiceLooper = thread.getLooper();
		mServcieHandler = new ServiceHandler(mServiceLooper);

		String ns = Context.NOTIFICATION_SERVICE;
		mNotificationManager = (NotificationManager) getSystemService(ns);

		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	private Runnable mUpdateLocationRunnable = new Runnable() {

		@Override
		public void run() {
			try {
				if (MyApp.sGlobleCertificate != null) {
					List<String> providers = locationManager.getProviders(true);
					for (String item : providers) {
						Location loc = locationManager
								.getLastKnownLocation(item);
						if (loc != null) {
							String myLatitude = String.valueOf(loc
									.getLatitude());
							String myLongitude = String.valueOf(loc
									.getLongitude());
							try {
								mWebServiceClient.MyLongitudeAndLatitude(
										MyApp.sGlobleCertificate,
										Float.valueOf(myLongitude),
										Float.valueOf(myLatitude));
							} catch (NumberFormatException e) {
							} catch (IOException e) {
							} catch (XmlPullParserException e) {
							}
						}
					}
				}
			} catch (Exception e) {
			}

			// 每隔1小时
			mServcieHandler
					.postDelayed(mUpdateLocationRunnable, 60 * 1000 * 60);
		}
	};

	private Runnable mRequireInternalMessageRunnable = new Runnable() {
		@Override
		public void run() {
			Log.d(TAG, "mRequireInternalMessageRunnable");
			try {
				if (MyApp.sGlobleCertificate != null) {
					Object object = mWebServiceClient
							.requireNewInternalMessage(MyApp.sGlobleCertificate);
					if (object instanceof SoapPrimitive) {
						SoapPrimitive sp = (SoapPrimitive) object;
						if (Boolean.valueOf(sp.toString())) {
							Log.d(TAG, "有消息");
							String notificationText = "";
							Object response = mWebServiceClient
									.commonGetMyInternalMessage(MyApp.sGlobleCertificate);
							SoapObject soap;
							String content = "";
							StringBuilder sb = new StringBuilder();
							Wl156DB db = new Wl156DB(MyService.this);
							String[] v = new String[7];

							if (response instanceof SoapObject) {
								soap = (SoapObject) response;
								for (int i = 0; i < soap.getPropertyCount(); i++) {
									SoapObject line = (SoapObject) soap
											.getProperty(i);
									String id = Utils.propertyToShow(line
											.getProperty(0));
									String type = Utils.propertyToShow(line
											.getProperty(1));
									String title = Utils.propertyToShow(line
											.getProperty(2));
									String carGoodType = Utils
											.propertyToShow(line.getProperty(3));
									String carOrGoodId = Utils
											.propertyToShow(line.getProperty(4));
									String date = Utils.propertyToShow(line
											.getProperty(5));
									try {
										content = Utils.propertyToShow(line
												.getProperty(6));
									} catch (Exception e) {
										content = "";
									}
									notificationText = title;
									v[0] = id;
									v[1] = type;
									v[2] = title;
									v[3] = date;
									v[4] = content;
									v[5] = carGoodType;
									v[6] = carOrGoodId;
									if (type.equals("特殊类型")) {
										String[] updateValues = new String[1];
										updateValues[0] = id;
										db.getWritableDatabase()
												.execSQL(
														"update internal_message set content='已成交' where id=?",
														updateValues);
									} else {
										db.getWritableDatabase()
												.execSQL(
														"insert into internal_message (id, type, title, date, content, carGoodType, carOrGoodId) "
																+ "values(?, ?, ?, ?, ?, ?, ?)",
														v);
									}
									sb.append(id).append("##").append(type)
											.append("##").append(title)
											.append("##").append(date)
											.append("##").append(content)
											.append("@@");

								}

								Intent i = new Intent();
								i.setAction("has_new_message");
								sendBroadcast(i);
							}
							db.close();

							CharSequence tickerText = "你有新的信息!";
							long when = System.currentTimeMillis();

							Notification notification = new Notification(
									R.drawable.icon, tickerText, when);
							Context context = getApplicationContext();
							CharSequence contentTitle = "你有新的信息";
							CharSequence contentText = notificationText;
							Intent notificationIntent = new Intent(
									MyService.this, InternalMessage.class);
							notificationIntent.putExtra("msg", sb.toString());

							PendingIntent contentIntent = PendingIntent
									.getActivity(MyService.this, 0,
											notificationIntent,
											PendingIntent.FLAG_UPDATE_CURRENT);

							notification.flags |= Notification.FLAG_AUTO_CANCEL;
							notification.defaults |= Notification.DEFAULT_ALL;
							notification.setLatestEventInfo(context,
									contentTitle, contentText, contentIntent);

							mNotificationManager.notify(HELLO_ID, notification);
						} else {
							Log.d(TAG, "没有消息");
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			mServcieHandler.postDelayed(mRequireInternalMessageRunnable,
					60 * 1000);
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "onStartCommand");

		mServcieHandler.post(mRequireInternalMessageRunnable);

		mServcieHandler.post(mUpdateLocationRunnable);

		return START_STICKY;
	}
}
